I recently teamed up with Mauricio Vargas Sepúlveda to create some graphing tutorials in R. In the coming weeks, we will be publishing a series of tutorials on how to use the ggplot2 package to create beautiful and informative data visualisations. Each tutorial will explain how to create a different type of plot, and will take you step-by-step from a basic plot to a highly customised graph.
In this first tutorial, we will demonstrate some of the many options the ggplot2 package has for creating and customising line plots. We will use an international trade dataset made by ourselves from different sources (Chile Customs, Central Bank of Chile and General Directorate of International Economic Relations).
The first thing to do is load in the data and libraries, as below:
library(ggplot2)
library(ggthemes)
library(extrafont)
charts.data <- read.csv("copper-data-for-tutorial.csv")
In this tutorial, we will work towards creating the line plot below. We will take you from a basic line plot and explain all the customisations we add to the code step-by-step.
In order to initialise a plot we tell ggplot that charts.data is our data, and specify the variables on each axis. We then instruct ggplot to render this as a line plot by adding the geom_line command.
p1 <- ggplot() + geom_line(aes(y = export, x = year, colour = product),
data = charts.data, stat="identity")
p1
To change the line width, we add a size argument to geom_line.
p1 <- ggplot() + geom_line(aes(y = export, x = year, colour = product), size=1.5,
data = charts.data, stat="identity")
p1
To change the variables displayed name, we need to re-factor our data labels in charts.data data frame. Then we move the legend to the bottom using the theme command.
charts.data <- as.data.frame(charts.data)
charts.data$product <- factor(charts.data$product, levels = c("copper","others"),
labels = c("Copper","Pulp wood, Fruit, Salmon & Others"))
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5, data = charts.data, stat="identity") +
theme(legend.position="bottom", legend.direction="horizontal", legend.title = element_blank())
p1
To change the axis tick marks, we use the scale_x_continuous and/or scale_y_continuous commands.
p1 <- p1 + scale_x_continuous(breaks=seq(2006,2014,1))
p1
To add a title, we include the option ggtitle and include the name of the graph as a string argument, and to change the axis names we use the labs command.
p1 <- p1 + ggtitle("Composition of Exports to China ($)") + labs(x="Year", y="USD million")
p1
To change the colours, we use the scale_colour_manual command.
colour <- c("#5F9EA0", "#E1B378")
p1 <- p1 + scale_colour_manual(values=colour)
p1
We’ll start using a simple theme customisation made adding theme_bw() after ggplot(). That theme argument can be modified to use different themes.
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5, data = charts.data,
stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_colour_manual(values=colour) +
theme_bw() +
theme(legend.position="bottom",
legend.direction="horizontal",
legend.title = element_blank())
p1
Of course, you may want to create your own themes as well. ggplot2 allows for a very high degree of customisation, including allowing you to use imported fonts. Below is an example of a theme Mauricio was able to create which mimics the visual style of XKCD. In order to create this chart, you first need to import the XKCD font, install it on your machine and load it into R using the extrafont package. These instructions are taken from here:
library(extrafont)
download.file("http://simonsoftware.se/other/xkcd.ttf",
dest="xkcd.ttf", mode="wb")
system("mkdir ~/.fonts")
system("cp xkcd.ttf ~/.fonts")
font_import(paths = "~/.fonts", pattern="[X/x]kcd")
fonts()
loadfonts()
You can then create your graph:
fill <- c("#56B4E9", "#ff69b4")
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5, data = charts.data,
stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_color_manual(values=fill) +
theme(axis.text.x=element_text(colour="black", size = 10),
axis.text.y=element_text(colour="black", size = 10),
axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
legend.key=element_rect(fill="white", colour="white"),
legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), panel.border = element_blank(),
panel.background = element_blank(),
plot.title=element_text(family="xkcd-Regular"), text=element_text(family="xkcd-Regular"))
p1
There are a wider range of pre-built themes available as part of the ggthemes package (more information on these here). Below we’ve applied theme_economist(), which approximates graphs in the Economist magazine. It is also important that the font change argument inside theme is optional and it’s only to obtain a more similar result compared to the original. For an exact result you need ‘Officina Sans’ which is a commercial font and is available here.
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5, data = charts.data,
stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
theme_economist() + scale_colour_economist() +
theme(axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
legend.position="bottom",
legend.direction="horizontal",
legend.title = element_blank(),
plot.title=element_text(family="OfficinaSanITC-Book"),
text=element_text(family="OfficinaSanITC-Book"))
p1
As before, you can modify your plots a lot as ggplot2 allows many customisations. Here we present our original result shown at the top of page.
colour <- c("#40b8d0", "#b2d183")
p1 <- ggplot() +
geom_line(aes(y = export, x = year, colour = product), size=1.5, data = charts.data,
stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_colour_manual(values=colour) +
theme(axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
axis.text.x=element_text(colour="black", size = 10),
axis.text.y=element_text(colour="black", size = 10),
legend.key=element_rect(fill="white", colour="white"),
legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank(),
panel.grid.major = element_line(colour = "#d3d3d3"),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
text=element_text(family="Tahoma"))
p1
In this second tutorial I am doing with Mauricio Vargas Sepúlveda, we will demonstrate some of the many options the ggplot2 package has for creating and customising area plots. We will use the same dataset from the first post.
In this tutorial, we will work towards creating the area plot below. We will take you from a basic area plot and explain all the customisations we add to the code step-by-step.
The first thing to do is load in the data and libraries, as below:
library(ggplot2)
library(ggthemes)
library(extrafont)
library(plyr)
charts.data <- read.csv("copper-data-for-tutorial.csv")
In order to initialise a plot we tell ggplot that charts.data is our data, and specify the variables on each axis. We then instruct ggplot to render this as an area plot by adding the geom_area command.
charts.data <- read.csv("copper-data-for-tutorial.csv")
p2 <- ggplot() + geom_area(aes(y = export, x = year, fill = product), data = charts.data,
stat="identity")
p2
To adjust the position of the legend from the default spot of right of the graph, we add the theme option and specify the legend.position="bottom" argument. We can also change the title to blank using the legend.title = element_blank() argument and change the legend shape using the legend.direction="horizontal" argument.
charts.data <- ddply(charts.data, .(year), transform, pos = cumsum(export) - (0.5 * export))
p2 <- p2 + theme(legend.position="bottom", legend.direction="horizontal", legend.title = element_blank())
p2
To change the variables displayed name, we need to re-factor our data labels in charts.data data frame.
charts.data <- as.data.frame(charts.data)
charts.data$product <- factor(charts.data$product, levels = c("copper","others"),
labels = c("Copper","Pulp wood, Fruit, Salmon & Others"))
p2 <- ggplot() +
geom_area(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
theme(legend.position="bottom", legend.direction="horizontal", legend.title = element_blank())
p2
To change the axis tick marks, we use the scale_x_continuous and/or scale_y_continuous commands.
p2 <- p2 + scale_x_continuous(breaks=seq(2006,2014,1))
p2
To add a title, we include the option ggtitle and include the name of the graph as a string argument, and to change the axis names we use the labs command.
p2 <- p2 + ggtitle("Composition of Exports to China ($)") +
labs(x="Year", y="USD million")
p2
To change the colours, we use the scale_colour_manual command. Note that you can reference the specific colours you’d like to use with specific HEX codes. You can also reference colours by name, with the full list of colours recognised by R here.
fill <- c("#5F9EA0", "#E1B378")
p2 <- p2 + scale_fill_manual(values=fill)
p2
As explained in the previous post, we can also change the overall look of the site using themes. We’ll start using a simple theme customisation by adding theme_bw() after ggplot(). As you can see, we can further tweak the graph using the theme option, which we’ve used so far to change the legend.
p2 <- ggplot() +
geom_area(aes(y = export, x = year, fill = product), data = charts.data,
stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_fill_manual(values=fill) +
theme_bw() +
theme(legend.position="bottom",
legend.direction="horizontal",
legend.title = element_blank())
p2
Of course, you may want to create your own themes as well. ggplot2 allows for a very high degree of customisation, including allowing you to use imported fonts. Below is an example of a theme Mauricio was able to create which mimics the visual style of XKCD. In order to create this chart, you first need to import the XKCD font, install it on your machine and load it into R using the extrafont package. These instructions are taken from here:
library(extrafont)
download.file("http://simonsoftware.se/other/xkcd.ttf",
dest="xkcd.ttf", mode="wb")
system("mkdir ~/.fonts")
system("cp xkcd.ttf ~/.fonts")
font_import(paths = "~/.fonts", pattern="[X/x]kcd")
fonts()
loadfonts()
You can then create your graph:
fill <- c("#56B4E9", "#ff69b4")
p2 <- ggplot() +
geom_area(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_fill_manual(values=fill) +
theme(axis.text.x=element_text(colour="black", size = 10),
axis.text.y=element_text(colour="black", size = 10),
axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
legend.key=element_rect(fill="white", colour="white"),
legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), panel.border = element_blank(),
panel.background = element_blank(),
plot.title=element_text(family="xkcd-Regular"), text=element_text(family="xkcd-Regular"))
p2
There are a wider range of pre-built themes available as part of the ggthemes package (more information on these here). Below we’ve applied theme_economist(), which approximates graphs in the Economist magazine. It is also important that the font change argument inside theme is optional and it’s only to obtain a more similar result compared to the original. For an exact result you need ‘Officina Sans’ which is a commercial font and is available here.
p2 <- ggplot() +
geom_area(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
theme_economist() + scale_fill_economist() +
theme(axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
legend.position="bottom",
legend.direction="horizontal",
legend.title = element_blank(),
plot.title=element_text(family="OfficinaSanITC-Book"),
text=element_text(family="OfficinaSanITC-Book"))
p2
As before, you can modify your plots a lot as ggplot2 allows many customisations. Here we present our original result shown at the top of page.
fill <- c("#40b8d0", "#b2d183")
p2 <- ggplot() +
geom_area(aes(y = export, x = year, fill = product), data = charts.data,
stat="identity") +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_fill_manual(values=fill) +
theme(axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
axis.text.x=element_text(colour="black", size = 10),
axis.text.y=element_text(colour="black", size = 10),
legend.key=element_rect(fill="white", colour="white"),
legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank(),
panel.grid.major = element_line(colour = "#d3d3d3"),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
text=element_text(family="Tahoma"))
p2
In this third tutorial I am doing with Mauricio Vargas Sepúlveda, we will demonstrate some of the many options the ggplot2 package has for creating and customising bar plots. We will use the same dataset from the first post.
In this tutorial, we will work towards creating the area plot below. We will take you from a basic bar plot and explain all the customisations we add to the code step-by-step.
The first thing to do is load in the data and libraries, as below:
library(ggplot2)
library(ggthemes)
library(extrafont)
library(plyr)
library(scales)
charts.data <- read.csv("copper-data-for-tutorial.csv")
In order to initialise a plot we tell ggplot that charts.data is our data, and specify the variables on each axis. We then instruct ggplot to render this as an bar plot by adding the geom_area command.
p3 <- ggplot() + geom_bar(aes(y = export, x = year, fill = product), data = charts.data,
stat="identity")
p3
To label the bars according to some variable in the data, we add the label argument to the ggplot(aes()) option. In this case, we have labelled the bars with numbers from the export variable.
p3 <- p3 + geom_text(data=charts.data, aes(x = year, y = export, label = export), size=4)
p3
To adjust the position of the data labels from the default placement, we use the ddply function on the data, and create a new variable called pos. This variable is at the centre of each bar and can be used to specify the position of the labels by assigning it to the y argument in geom_text(aes()).
charts.data <- ddply(charts.data, .(year), transform, pos = cumsum(export) - (0.5 * export))
p3 <- ggplot() + geom_bar(aes(y = export, x = year, fill = product), data = charts.data,
stat="identity")
p3 <- p3 + geom_text(data=charts.data, aes(x = year, y = pos, label = export), size=4)
p3
To adjust the position of the legend from the default spot of right of the graph, we add the theme option and specify the legend.position="bottom" argument. We can also change the title to blank using the legend.title = element_blank() argument and change the legend shape using the legend.direction="horizontal" argument.
p3 <- p3 + theme(legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank())
p3
To change the variables’ displayed name, we need to re-factor our data labels in charts.data data frame.
charts.data$product <- factor(charts.data$product, levels = c("copper","others"),
labels = c("Copper","Pulp wood, Fruit, Salmon & Others"))
p3 <- ggplot() + geom_bar(aes(y = export, x = year, fill = product), data = charts.data,
stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export, size=4),
show.legend = F) +
theme(legend.position="bottom", legend.direction="horizontal", legend.title = element_blank())
p3
To change the axis tick marks, we use the scale_x_continuous and/or scale_y_continuous commands.
p3 <- p3 + scale_x_continuous(breaks=seq(2006,2014,1))
p3
To add a title, we include the option ggtitle and include the name of the graph as a string argument, and to change the axis names we use the labs command.
p3 <- p3 + ggtitle("Composition of Exports to China ($)") + labs(x="Year", y="USD million")
p3
To change the colours, we use the scale_colour_manual command. Note that you can reference the specific colours you’d like to use with specific HEX codes. You can also reference colours by name, with the full list of colours recognised by R here.
fill <- c("#5F9EA0", "#E1B378")
p3 <- p3 + scale_fill_manual(values=fill)
p3
As explained in the previous posts, we can also change the overall look of the graph using themes. We’ll start using a simple theme customisation by adding theme_bw() after ggplot(). As you can see, we can further tweak the graph using the theme option, which we’ve used so far to change the legend.
p3 <- ggplot() +
geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export, size=4), show.legend = F) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_fill_manual(values=fill) +
theme_bw() +
theme(legend.position="bottom",
legend.direction="horizontal",
legend.title = element_blank())
p3
Of course, you may want to create your own themes as well. ggplot2 allows for a very high degree of customisation, including allowing you to use imported fonts. Below is an example of a theme Mauricio was able to create which mimics the visual style of XKCD. In order to create this chart, you first need to import the XKCD font, install it on your machine and load it into R using the extrafont package. These instructions are taken from here:
library(extrafont)
download.file("http://simonsoftware.se/other/xkcd.ttf",
dest="xkcd.ttf", mode="wb")
system("mkdir ~/.fonts")
system("cp xkcd.ttf ~/.fonts")
font_import(paths = "~/.fonts", pattern="[X/x]kcd")
fonts()
loadfonts()
You can then create your graph:
fill <- c("#56B4E9", "#F0E442")
p3 <- ggplot() +
geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export), colour="black",
family="xkcd-Regular", size = 4, show.legend = F) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_fill_manual(values=fill) +
theme(axis.text.x=element_text(colour="black", size = 10),
axis.text.y=element_text(colour="black", size = 10),
axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
legend.key=element_rect(fill="white", colour="white"),
legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), panel.border = element_blank(),
panel.background = element_blank(),
plot.title=element_text(family="xkcd-Regular"), text=element_text(family="xkcd-Regular"))
p3
There are a wider range of pre-built themes available as part of the ggthemes package (more information on these here). Below we’ve applied theme_economist(), which approximates graphs in the Economist magazine. It is also important that the font change argument inside theme is optional and it’s only to obtain a more similar result compared to the original. For an exact result you need ‘Officina Sans’ which is a commercial font and is available here.
p3 <- ggplot() +
geom_bar(aes(y = export, x = year, fill = product), data = charts.data,
stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export), colour="white", size = 4,
family = "OfficinaSanITC-Book", show.legend = F) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
theme_economist() + scale_fill_economist() +
theme(axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
legend.position="bottom",
legend.direction="horizontal",
legend.title = element_blank(),
plot.title=element_text(family="OfficinaSanITC-Book"),
text=element_text(family="OfficinaSanITC-Book"))
p3
As before, you can modify your plots a lot as ggplot2 allows many customisations. Here we present our original result shown at the top of page.
fill <- c("#40b8d0", "#b2d183")
p3 <- ggplot() +
geom_bar(aes(y = export, x = year, fill = product), data = charts.data, stat="identity") +
geom_text(data=charts.data, aes(x = year, y = pos, label = export), colour="black",
family="Tahoma", size = 4, show.legend = F) +
scale_x_continuous(breaks=seq(2006,2014,1)) +
labs(x="Year", y="USD million") +
ggtitle("Composition of Exports to China ($)") +
scale_fill_manual(values=fill) +
theme(axis.line.x = element_line(size=.5, colour = "black"),
axis.line.y = element_line(size=.5, colour = "black"),
axis.text.x=element_text(colour="black", size = 10),
axis.text.y=element_text(colour="black", size = 10),
legend.key=element_rect(fill="white", colour="white"),
legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank(),
panel.grid.major = element_line(colour = "#d3d3d3"),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
text=element_text(family="Tahoma"))
p3